<?php
/**
 * 支付宝支付
 * @author chenlisong E-mail:chenlisong1021@163.com 
 * @version 创建时间：2016年8月28日 上午9:46:14 
 * 类说明
 */
class AlipayAction extends BaseAction{
	
	public function _initialize(){
		$this->param = $_REQUEST;
		vendor("Alipayformobile.lib.alipay_core#function");
		vendor("Alipayformobile.lib.alipay_notify#class");
		vendor("Alipayformobile.lib.alipay_rsa#function");
	}
	
	public function index(){
		echo $this->err("非法操作！");
	}
	
	/**
	 * 支付宝支付
	 */
	public function alipayPayOrder(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');$Product = M('Product');$ShopProduct = M("ShopProduct");$ShopAttributeValues = M("ShopAttributeValues");
		$param = $this->param;
		if(empty($param['orderCode'])){
			echo $this->err("参数错误！");
			return ;
		}
		//判断订单状态是否正确
		$where['code'] = $param['orderCode'];
		$where['flag'] = 1;
		$where['status'] = 1;
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			echo $this->err("错误的订单状态，请重新下单！");
			return ;
		}
		//封装body
		$map['order_code'] = $param['orderCode'];
		$map['flag'] = 1;
		$goodslist = $OrderDetails->where($map)->field('name,num,product_id,attribute_values')->select();
		$body = '';
		foreach ($goodslist as $key=>$val){
			$productInfo = $Product->field('name,num,is_on')->where(array('id' => $val['product_id'], 'flag' => 1))->find();
			$shopProductInfo = $ShopProduct->field("num")->where(array('product_id' => $val['product_id'], 'flag' => 1,'shop_id'=>$info['shop_id']))->find();
			$sellNum = $val['num'];
			if ($val['attribute_values'] != "") {
				$attr_value_arr = explode(':', $val['attribute_values']);
				$attr_value_name = $attr_value_arr[1];
				$attribute_values = $ShopAttributeValues->where(array("product_id" => $val['product_id'],'flag' => 1, 'attr_value_name' => $attr_value_name,'shop_id'=>$info['shop_id']))->find();
				if ($attribute_values) {
					if ($sellNum > $attribute_values['num']) {
						echo $this->err($val['name'] . '库存不足，请重新选择商品！');
						return;
					}
				}
			} else {
				if ($sellNum > $shopProductInfo['num']) {
					echo $this->err($val['name'] . '库存不足，请重新选择商品！');
					return;
				}
			}
			//商品下架
			if ($productInfo['is_on'] == 2) {
				echo $this->err($val['name'] . '已下架，请重新选择商品！');
				return;
			}
			$body .= $val['name'].$val['num']."份.";

		}
		$name = '佳好友网络订单，单号：'.$param['orderCode'];
		$url = C('APP_ALIPAY_ORDER_NOTIFY_URL');//回调地址
		$price = ($info['real_price'] + $info['mail_fee']);//加上运费
		//组装请求参数
		$data = $this->getAlipayAppParam($param['orderCode'], $name, $price, $body,$url);
		echo $this->suc($data);
	}
	
	
	/**
	 * 支付宝支付回调函数
	 *
	 */
	public function orderNotifyReturn(){
		$alipay_config = C('alipay_app_config');
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {//验证成功
			$code = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$trade_status = $_POST['trade_status'];//交易状态
			$total_fee = $_POST['total_fee'];//交易金额
			$buyer_email = $_POST['buyer_email'];//交易金额
			if($_POST['trade_status'] == 'TRADE_FINISHED') {
				//处理订单
				$this->handleOrder($code,$trade_no,$buyer_email);
			}else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//处理订单
				$this->handleOrder($code,$trade_no,$buyer_email);
				echo "success";		//请不要修改或删除
			}
		}else {
			echo "fail";
			$msg = "[".$_POST['gmt_payment']."]".$_POST['out_trade_no'].'充值订单使用支付宝支付失败！买家支付宝号：'.$_POST['buyer_email'].",交易号为：".$_POST['trade_no'].",商品为：".$_POST['body'];
			writeLog("【订单支付】：".$msg);
		}
	}
	
	private function handleOrder($code,$trade_no,$buyer_email){
		//付款成功进行订单处理
		$Order = M('Order');$Shop = M('Shop');$OrderDetails = M('OrderDetails');$Product = M('Product');$ShopProduct = M("ShopProduct");$ShopAttributeValues = M("ShopAttributeValues");
		$where['code'] = $code;
		$info = $Order->where($where)->find();
		if(in_array($info['status'], array(1,-1))){
			$Shopinfo = $Shop->where(array("id"=>$info['shop_id']))->field("user_id")->find();
			$this->insertNotice($Shopinfo['user_id'],"您有未处理的订单！",$info['code']);
			//订单状态更改
			$data['status'] = 2;
			$data['flag'] = 1;
			$data['pay_type'] = 1;
			$data['pay_time'] = time();
			$data['pay_code'] = $trade_no;
			$data['pay_email'] = $buyer_email;
			$data['update_time'] = time();
			$Order->where($where)->save($data);

			//扣除库存
			$orderDetails = $OrderDetails->where(array('order_code'=>$info['code'],'flag'=>1))->select();
			//$querySql = 'SET num = CASE id ';
			//$queryIds = "";

			$querySql_s = 'SET num = CASE product_id ';
			$queryIds_s = "";

			$querySql_1 = 'SET num = CASE id ';
			$queryIds_1 = "";

			foreach ($orderDetails as $pk => $pv) {
				$sellNum = $pv['num'];
				//组装扣除商品数量sql
				if ($pv['attribute_values'] != "") {
					$querySql_1 .= ' WHEN ' . $pv['attr_values_id'] . ' THEN num -' . $sellNum . " ";
					$queryIds_1 .= $pv['attr_values_id'] . ",";
				} else {
					// $querySql .= ' WHEN ' . $pv['product_id'] . ' THEN num -' . $sellNum . " ";
					// $queryIds .= $pv['product_id'] . ",";
					$querySql_s .= ' WHEN ' . $pv['product_id'] . ' THEN num -' . $sellNum . " ";
					$queryIds_s .= $pv['product_id'] . ",";
				}

			}

			if ($queryIds_1 != '') {
				$querySql_1 .= ' END ';
				$queryIds_1 = substr($queryIds_1, 0, strlen($queryIds_1) - 1);
				$querySql_1 .= 'where flag=1 and id in (' . $queryIds_1 . ') and shop_id='.$info['shop_id'];
			}
			/*
			if ($queryIds != '') {
				$querySql .= ' END ';
				$queryIds = substr($queryIds, 0, strlen($queryIds) - 1);
				$querySql .= 'where id in (' . $queryIds . ')';
			}
			*/

			if ($queryIds_s != '') {
				$querySql_s .= ' END ';
				$queryIds_s = substr($queryIds_s, 0, strlen($queryIds_s) - 1);
				$querySql_s .= 'where  flag=1 and product_id in (' . $queryIds_s . ') and shop_id=' . $info['shop_id'];
			}

			//扣除商品表库存
			/*
			if ($queryIds != '') {
				$Product->execute('update __TABLE__ ' . $querySql);
			}
			*/
			//扣除规格库存
			if ($queryIds_1 != '') {
				$ShopAttributeValues->execute('update __TABLE__ ' . $querySql_1);
			}
			//扣除店铺商品库存
			if ($queryIds_s != '') {
				$ShopProduct->execute('update __TABLE__ ' . $querySql_s);
			}


		}else{
			$msg = "交易号为：".$trade_no."，订单编号为".$code."使用支付宝支付完成，但是订单状态为非正常状态！";
			writeLog($msg);
		}
		return true;
	}
	
	/**
	 * 支付宝充值
	 */
	public function recharge(){
		$RechargeSetting = M('RechargeSetting');$RechargeLog = M('RechargeLog');
		$param = $this->param;
		$where['flag'] = 1;
		$where['id'] = $param['rechargeId'];
		$info = $RechargeSetting->where($where)->find();
		if(empty($info)){
			echo $this->err("错误的充值金额！");
			return;
		}
		$code = date('YmdHis').rand(10,99);
		$data['code'] = $code;
		$data['user_id'] = $param['userId'];
		$data['recharge_price'] = $info['recharge_price'];
		$data['give_price'] = $info['give_price'];
		$data['create_time'] = time();
		$RechargeLog->add($data);
		$body = "在线充值".$info['recharge_price']."返利".$info['give_price'];
		$name = '佳好友在线充值';
		$url = C('APP_ALIPAY_RECHARGE_NOTIFY_URL');//回调地址
		//组装请求参数
		$data = $this->getAlipayAppParam($code, $name, $info['recharge_price'], $body,$url);
		echo $this->suc($data);
		
	}
	
	/**
	 * 充值成功回调
	 */
	public function rechargeNotifyReturn(){
		$alipay_config = C('alipay_app_config');
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {//验证成功
			$code = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$trade_status = $_POST['trade_status'];//交易状态
			$total_fee = $_POST['total_fee'];//交易金额
			$buyer_email = $_POST['buyer_email'];//交易金额
			if($_POST['trade_status'] == 'TRADE_FINISHED') {
				//处理订单
				$this->handleRecharge($code,$trade_no,$buyer_email);
			}else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//处理订单
				$this->handleRecharge($code,$trade_no,$buyer_email);
				echo "success";		//请不要修改或删除
			}
		}else {
			echo "fail";
			$msg = "[".$_POST['gmt_payment']."]".$_POST['out_trade_no'].'充值订单使用支付宝支付失败！买家支付宝号：'.$_POST['buyer_email'].",交易号为：".$_POST['trade_no'].",商品为：".$_POST['body'];
			writeLog("【充值】：".$msg);
		}
	}
	
	private function handleRecharge($code,$trade_no,$buyer_email){
		//付款成功进行订单处理
		$RechargeLog = M('RechargeLog');$User = M('User');$UserDetails = M('UserDetails');$Fields = M('Fields');
		$where['code'] = $code;
		$info = $RechargeLog->where($where)->find();
		$balance = (float) $User->where('id = '.$info['user_id'])->getField('balance');
		if(in_array($info['status'], array(1,-1))){
			//给用户加金额（含赠送）
			$data[0]['user_id'] = $info['user_id'];
			$data[0]['title'] = "支付宝充值";
			$data[0]['type'] = 1;
			$data[0]['price'] = $info['recharge_price'];
			$data[0]['last_price'] = $balance;
			$data[0]['create_time'] = time();
			$data[1]['user_id'] = $info['user_id'];
			$data[1]['title'] = "充值赠送";
			$data[1]['type'] = 1;
			$data[1]['price'] = $info['give_price'];
			$data[1]['last_price'] = $balance + $info['recharge_price'];
			$data[1]['create_time'] = time();
			$UserDetails->addAll($data);
			$User->where('id = '.$info['user_id'])->setInc('balance',($info['recharge_price'] + $info['give_price']));
			//给推荐人分润
			$parentId = $User->where('id = '.$info['user_id'])->getField('parent_id');
			if(!empty($parentId)){
				$bl = (float) $Fields->where('flag = 1 and field ="app_recharge_return_rate"')->getField('value');
				$price = sprintf("%.2f",$info['recharge_price'] * $bl);
				$udata['user_id'] = $parentId;
				$udata['title'] = "充值返利";
				$udata['type'] = 1;
				$udata['price'] = $price;
				$udata['from_user_id'] = $info['user_id'];
				$udata['last_price'] = (float) $User->where('id = '.$parentId)->getField('balance');;
				$udata['create_time'] = time();
				$UserDetails->add($udata);
				$User->where('id = '.$parentId)->setInc('balance',$price);
			}
			//订单状态更改
			$dataOrder['status'] = 2;
			$dataOrder['flag'] = 1;
			$dataOrder['pay_type'] = 1;
			$dataOrder['pay_time'] = time();
			$dataOrder['pay_code'] = $trade_no;
			$dataOrder['pay_email'] = $buyer_email;
			$dataOrder['update_time'] = time();
			$RechargeLog->where($where)->save($dataOrder);
		}else{
			$msg = "【充值】交易号为：".$trade_no."，订单编号为".$code."使用支付宝支付完成，但是订单状态为非正常状态！";
			writeLog($msg);
		}
		return true;
	}
	
	/**
	 * 支付宝组装签名
	 * @param 订单编号 $code
	 * @param 商品名称 $name
	 * @param 总金额 $real_price
	 * @param 商品详情 $body
	 * @param 回调地址 $url
	 * @return string
	 */
	private function getAlipayAppParam($code,$name,$real_price,$body,$url){
		//组装签名
		$ali = array(
				'partner' => C('alipay_app_config.partner'),
				'out_trade_no' => $code,//商户网站唯一订单号
				'subject' => $name,//商品名称
				'body' => $body,//商品详情
				'total_fee' => $real_price,//总金额
				'notify_url' => urlencode($url),//回调地址
				'service' => 'mobile.securitypay.pay',
				'_input_charset' => 'utf-8',
				'payment_type' => 1,//支付类型
				'seller_id' => C('APP_ALIPAY_SELLER_ID'),//支付宝账号
				'it_b_pay' => '1m',//m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。该参数数值不接受小数点
				'sign' => '',
				'sign_type' => C('alipay_app_config.sign_type'),//签名方式RSA
		);
		$ali = argSort($ali);
		$args = paraFilter($ali);//去除参数中的sign和sign_type
		$args = createLinkstring($args);//把数组按&连接
		$sign = rsaSign($args, C('alipay_app_config.private_key_path'));
		$data = $args.'&sign='.'"'.urlencode($sign).'"'.'&sign_type='.'"'.$ali['sign_type'].'"';//传给支付宝接口的数据
		return $data;
	}

	/**
	 * 新增消息
	 * 新增商家待处理订单消息
	 */
	private function insertNotice($userId,$message,$ambulance){
		$Notice = M('Notice');$User = M('User');
		$jpushId = $User->where('id = '.$userId)->getField('jpush_id');
		if(!empty($jpushId)){
			$data['type'] = 4;
			$data['user_id'] = $userId;
			$data['message'] = $message;
			$data['ambulance'] = $ambulance;
			$data['create_time'] = time();
			$Notice->add($data);
		}
		return true;
	}
}